using UnityEngine;
using System.Collections;

public class GameCamera : MonoBehaviour {

	public float distance = 0;
	public Transform target;
	//public float trackSpeed = 5;
	public float trackTime;
	public float reactionTime;
	public float reactionDistance;
	public Vector3 front, up;
	private float timer = 0;
	private bool onTrack = false;
	
	// Set target
	public void SetTarget(Transform t) {
		target = t;
	}

	public void SetTrackTime(float newTime){
		trackTime = newTime;
	}

	public void SetReacTime(float newTime){
		reactionTime = newTime;
	}

	public void SetReacDist(float newDistance){
		reactionDistance = newDistance;
	}

	// Track target
	void LateUpdate() {
		if(target != null){
			float XDiff = target.transform.position.x-transform.position.x;
			float YDiff = target.transform.position.y-transform.position.y;
			float distance = XDiff * XDiff + YDiff * YDiff;
			float sqrDisLimit = reactionDistance * reactionDistance;
			timer+=Time.deltaTime;
			if(!onTrack){
				if(timer > reactionTime || distance > sqrDisLimit){
					onTrack = true;
					//Debug.Log("starting tracking!! cause timer "+timer+" is bigger than period "+trackTime+" or distance "+distance+" is bigger than reacDis "+sqrDisLimit);
					timer = 0;
				}
			}else if(distance != 0){
				float percentage;
				if(trackTime == 0)	percentage = 1;
				else 				percentage = (1-Mathf.Cos(Mathf.Min(timer / trackTime, 1)*Mathf.PI))/2;
				float nextX = XDiff * percentage + transform.position.x;
				float nextY = YDiff * percentage + transform.position.y;
				transform.position = new Vector3(nextX, nextY, transform.position.z);
			}else{
				onTrack = false;
				timer = 0;
			}
		}
//		if (target != null) {
//			float x = IncrementTowards(transform.position.x, target.position.x, trackSpeed);
//			float y = IncrementTowards(transform.position.y, target.position.y, trackSpeed);
//			transform.position = new Vector3(x, y, transform.position.z);
//		}
	}
	
	// Increase n towards target by speed
	private float IncrementTowards(float n, float target, float a) {
		if (n == target) {
			return n;	
		}
		else {
			float dir = Mathf.Sign(target - n); // must n be increased or decreased to get closer to target
			n += a * Time.deltaTime * dir;
			return (dir == Mathf.Sign(target-n))? n: target; // if n has now passed target then return target, otherwise return n
		}
	}
}
